import { _decorator, AudioClip, Component, director, Node, sys } from 'cc';
import { BombUI } from './UI/BombUI';
import { ScoreUI } from './UI/ScoreUI';
import { Player } from './Player';
import { GameOverUI } from './UI/GameOverUI';
import { AudioMgr } from './AudioMgr';
const { ccclass, property } = _decorator;

@ccclass('GameManager')
export class GameManager extends Component {
    private static instance:GameManager;
    public static getInstance() {
        return this.instance;
    }
    @property
    bombNumber: number = 0;

    @property(BombUI)
    bombUI: BombUI = null;

    @property(ScoreUI)
    scoreUI: ScoreUI = null;
    
    @property
    private score: number = 0;

    @property(Player)
    player: Player = null;

    @property(Node)
    pauseButton: Node = null;

    @property(Node)
    resumeButton: Node = null;

    @property(GameOverUI)
    gameOverUI: GameOverUI = null;

    @property(AudioClip)
    bgMusic: AudioClip = null;

    @property(AudioClip)
    buttonAudio: AudioClip = null;
    
    @property(AudioClip)
    gameOverAudio: AudioClip = null;

    @property(AudioClip)
    useBombAudio: AudioClip = null;
    
    public addScore(s: number){
        this.score += s;
        this.scoreUI.updateUI(this.score);
    }

    start() {
        AudioMgr.inst.play(this.bgMusic, 0.2)
        GameManager.instance = this;
    }
    addBomb() {
        this.bombNumber += 1;
        this.bombUI.updateUI(this.bombNumber);
    }

    onPauseButtonClick() {
        AudioMgr.inst.playOneShot(this.buttonAudio);
        AudioMgr.inst.pause();
        director.pause();
        this.player.disableControl();
        this.pauseButton.active = false;
        this.resumeButton.active = true;
    }
    onResumeButtonClick() {
        AudioMgr.inst.playOneShot(this.buttonAudio)
        AudioMgr.inst.resume();
        director.resume();
        this.player.enableControl();
        this.resumeButton.active = false;
        this.pauseButton.active = true;
    }

    gameOver() {
        this.onPauseButtonClick();
        AudioMgr.inst.playOneShot(this.gameOverAudio);
        let hscore = sys.localStorage.getItem('highestScore');
        if(!hscore){
            hscore = 0;
        } else {
            hscore = parseInt(hscore);
        }
        if(this.score > hscore){
            sys.localStorage.setItem('highestScore', this.score.toString())
            hscore = this.score
        }

        this.gameOverUI.showGameOverUI(hscore, this.score);
    }

    onRestartButtonClick() {
        AudioMgr.inst.playOneShot(this.buttonAudio)
        director.loadScene(director.getScene().name);
        this.onResumeButtonClick();
    }

    onQuitButtonClick() {
        // 不做处理
    }

    hasBomb() {
        return this.bombNumber > 0;
    }

    useBomb() {
        this.bombNumber -= 1;
        AudioMgr.inst.playOneShot(this.useBombAudio)
        this.bombUI.updateUI(this.bombNumber);
    }
}


